package com.atguigu.gmall.activity.consumer;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.activity.mapper.SeckillGoodsMapper;
import com.atguigu.gmall.activity.mapper.SeckillOrderMapper;
import com.atguigu.gmall.activity.pojo.SeckillOrder;
import com.atguigu.gmall.activity.pojo.UserRecode;
import com.atguigu.gmall.activity.service.SeckillService;
import com.atguigu.gmall.model.activity.SeckillGoods;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author luYinLei
 * @version 1.0
 * @date 2021/7/17 22:00
 */
@Component
public class SeckillOrderUpdateListener {

    @Autowired
    private SeckillService seckillService;

    /**
     * 监听支付行为的秒杀队列，消息生产者这是支付微服务
     *
     * @param msg
     */
    @RabbitListener(queues = "seckill_queue")
    public void updateSeckillOrder(String msg) {
        //转换数据类型
        Map<String, String> payResult = JSONObject.parseObject(msg, Map.class);
        String payWay = payResult.get("payway");
        //判断
        if (payWay.equals("0")) {
            //支付宝逻辑
            Map<String, String> map = JSONObject.parseObject(msg, Map.class);
            //进行解析,获取请求的结果
            String tradeStatus = map.get("trade_status");
            if (!StringUtils.isEmpty(tradeStatus) && tradeStatus.equals("TRADE_SUCCESS")) {
                //支付成功，修改订单状态
                seckillService.paySuccess(map);
                //返回
                return;
            }
            //支付失败，修改订单状态
            seckillService.payFail(map);
        } else {
            //微信逻辑
            String returnCode = payResult.get("return_code");
            if (returnCode.equals("SUCCESS")) {
                //支付成功
                seckillService.paySuccess(payResult);
                return;
            }
            //支付失败
            seckillService.payFail(payResult);

        }
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    /**
     *监听超时未支付订单，延迟队列，秒杀订单
     * @param msg
     */
    @RabbitListener(queues = "seckill_normal_queue")
    public void cancleSeckillOrder(String msg){
        //转换类型
        SeckillOrder seckillOrder = JSONObject.parseObject(msg, SeckillOrder.class);
        //取消订单，判断前置状态
        if (seckillOrder!=null && seckillOrder.getStatus().equals("0")){
            //修改订单状态
            seckillOrder.setStatus("3");
            String username = seckillOrder.getUserId();
            //修改redis数据
            redisTemplate.boundHashOps("SeckillOrder_" + username).put(seckillOrder.getId(), seckillOrder);
            //存入数据库
            seckillOrderMapper.insert(seckillOrder);
            //回滚库存
            UserRecode userRecode = (UserRecode) redisTemplate.boundValueOps("SeckillStatus_" + username).get();
            rollBackSeckillGoodsNum(userRecode.getGoodsId(), userRecode.getTime(), userRecode.getNum());
            //删除排队表示
            redisTemplate.delete("SeckillUserQueue_"+username);
            //删除排队状态
            redisTemplate.delete("SeckillStatus_"+username);
        }

    }

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    /**
     * 回滚秒杀数据
     *
     * @param goodsId
     * @param time
     * @param num
     */
    private void rollBackSeckillGoodsNum(String goodsId, String time, Integer num) {
        //从redis获取商品数据
        SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_" + time).get(goodsId);
        if (seckillGoods == null) {
            //商品售罄，更新库存
            seckillGoodsMapper.updateSeckillGoodsStock(goodsId, num);
        } else {
            //redis中还有数据--更新redis中的库存数据
            String[] seckillGoodsQueue = getSeckillGoodsQueue(goodsId, num);
            redisTemplate.boundListOps("seckillGoodsQueue_" + goodsId).leftPushAll(seckillGoodsQueue);
            //回滚库存
            redisTemplate.boundHashOps("SeckillGoodsStockNum").increment(goodsId,num);

        }
    }

    /**
     * 库存长度的数组
     *
     * @param goodsId
     * @param stockCount
     */
    private String[] getSeckillGoodsQueue(String goodsId, Integer stockCount) {
        //构建数组
        String[] ids = new String[stockCount];
        //循环
        for (int i = 0; i <stockCount ; i++) {
            ids[i] = goodsId;
        }
        //返回
        return ids;
    }
}
